<script setup>
import { ref, computed, watch, watchEffect } from "vue";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { userAnswerApi } from "@/api/userAnswer";
import { optionCategoryApi } from "@/api/optionCategory";
import { generateSnowflakeId } from "@/utils/snowflakeId.js";

const optionCategories = ref([]);
const initialQuestion = ref();
const userAnswerId = ref();
const isTestFinished = ref(false);
const userAnswerGroupId = ref();

const token = ref(sessionStorage.getItem("pmp-token"));

const router = useRouter();
const loading = ref(false);

// 使用 watchEffect 监听 sessionStorage 变化
watchEffect(() => {
  // 监听 storage 事件，当其他标签页或窗口修改了 sessionStorage 时也能感知到
  const handleStorageChange = (e) => {
    if (e.key === 'pmp-token') {
      console.log('检测到 token 变化:', e.newValue ? '已登录' : '已登出');
      // 手动更新 token 的值
      token.value = e.newValue;
    }
  };
  
  // 监听当前页面的 sessionStorage 变化（通过定时器或自定义事件）
  const checkTokenChange = () => {
    const currentToken = sessionStorage.getItem("pmp-token");
    if (currentToken !== token.value) {
      console.log('检测到当前页面 token 变化:', currentToken ? '已登录' : '已登出');
      token.value = currentToken;
    }
  };
  
  // 定期检查 token 变化（每500ms检查一次）
  const intervalId = setInterval(checkTokenChange, 500);
  
  window.addEventListener('storage', handleStorageChange);
  
  // 清理监听器
  return () => {
    window.removeEventListener('storage', handleStorageChange);
    clearInterval(intervalId);
  };
});

// 计算当前选项分类的索引
const currentCategoryIndex = computed(() => {
  if (!initialQuestion.value?.optionCategoryId) return 0;
  return parseInt(initialQuestion.value.optionCategoryId) - 1;
});

// 获取当前选项分类
const currentCategory = computed(() => {
  return optionCategories.value[currentCategoryIndex.value] || null;
});

// 获取选项的颜色
const getOptionColor = (optionId, index) => {
  let colors = [];
  if (optionId === "1") {
    colors = [
      "#88619a",
      "#88619a",
      "#88619a",
      "#dddddd",
      "#33a474",
      "#33a474",
      "#33a474",
    ];
  } else if (optionId === "2") {
    colors = ["#88619a", "#88619a", "#dddddd", "#33a474", "#33a474"];
  } else if (optionId === "3") {
    colors = ["#88619a", "#88619a", "#33a474", "#33a474"];
  } else if (optionId === "4") {
    colors = ["#88619a", "#88619a", "#dddddd", "#33a474", "#33a474"];
  }
  return colors[index] || "#dddddd";
};

// 获取悬停时的颜色
const getHoverColor = (baseColor) => {
  const hoverColors = {
    "#33a474": "#2a8a5f", // 深绿色
    "#dddddd": "#c0c0c0", // 深灰色
    "#88619a": "#6f4f7d", // 深紫色
  };
  return hoverColors[baseColor] || baseColor;
};

// 获取选项大小
const getOptionSize = (optionId, index) => {
  let sizes = [];
  if (optionId === "1") {
    sizes = ["48px", "40px", "32px", "32px", "32px", "40px", "48px"];
  } else if (optionId === "2") {
    sizes = ["48px", "40px", "32px", "40px", "48px"];
  } else if (optionId === "3") {
    sizes = ["48px", "40px", "40px", "48px"];
  } else if (optionId === "4") {
    sizes = ["48px", "40px", "32px", "40px", "48px"];
  }
  return sizes[index] || "32px";
};

const nextQuestion = async (optionId) => {
  if (loading.value) return;

  loading.value = true;
  try {
    const params = {
      questionnaireId: 1,
      questionId: initialQuestion.value.id,
      optionId: optionId,
      userAnswerId: initialQuestion.value.userAnswerId,
      userAnswerGroupId: userAnswerGroupId.value,
    };
    const res = await userAnswerApi.submitSingleAnswer(params);
    if (res.success) {
      if (res.data === null) {
        initialQuestion.value = null;
        isTestFinished.value = true;
        sessionStorage.setItem("isTestFinished-pmpu", isTestFinished.value);
      } else {
        initialQuestion.value = res.data;
      }
    }
  } catch (error) {
    console.error("提交答案失败:", error);
  } finally {
    loading.value = false;
  }
};

const goToTestResults = () => {
  router.push(`/pmpu/results/${userAnswerGroupId.value}`);
};

const handleStartTest = async () => {
  userAnswerGroupId.value = generateSnowflakeId();
  sessionStorage.setItem("userAnswerGroupId-pmpu", userAnswerGroupId.value);
  const res = await userAnswerApi.submitSingleAnswer({
    questionnaireId: 1,
    userAnswerGroupId: userAnswerGroupId.value,
  });
  if (res.success) {
    initialQuestion.value = res.data;
    userAnswerId.value = res.data.userAnswerId;
    isTestFinished.value = false;
    sessionStorage.setItem("userAnswerId-pmpu", userAnswerId.value);
    sessionStorage.setItem("isTestFinished-pmpu", isTestFinished.value);
  }
};

// 重新开始测试
// const restartTest = () => {
//   isTestFinished.value = false;
//   userAnswerGroupId.value = generateSnowflakeId();
//   sessionStorage.setItem("userAnswerGroupId-pmpu", userAnswerGroupId.value);
//   sessionStorage.setItem("isTestFinished-pmpu", isTestFinished.value);
// };

onMounted(async () => {
  if (sessionStorage.getItem("option-categories")) {
    optionCategories.value = JSON.parse(
      sessionStorage.getItem("option-categories")
    );
  } else {
    const result = await optionCategoryApi.getAllOptionCategories();
    if (result.success) {
      optionCategories.value = result.data;
    }
    sessionStorage.setItem(
      "option-categories",
      JSON.stringify(optionCategories.value)
    );
  }
  isTestFinished.value =
    sessionStorage.getItem("isTestFinished-pmpu") === "true";
  userAnswerId.value = sessionStorage.getItem("userAnswerId-pmpu");
  userAnswerGroupId.value = sessionStorage.getItem("userAnswerGroupId-pmpu");
});
</script>

<template>
  <div>
    <img
      src="/src/assets/test.jpg"
      alt="test"
      class="object-cover w-full h-full -mt-16"
    />
    <div
      v-if="token"
      class="flex flex-col justify-center items-center gap-12 mt-10"
    >
      <div class="flex flex-col justify-center items-center gap-12 mt-10">
        <div class="text-[26px] text-[#576071]">
          {{ initialQuestion?.title }}
        </div>
        <template v-if="isTestFinished">
          <div class="flex items-center gap-4">
            <Button
              label="查看测试结果"
              icon="pi pi-chart-bar"
              @click="goToTestResults"
              class="bg-[#33a474] hover:bg-[#2a8a5f] border-[#33a474] hover:border-[#2a8a5f] transition-colors duration-300"
            />
            <!-- <Button
              label="重新开始"
              icon="pi pi-refresh"
              severity="secondary"
              @click="restartTest"
              class="bg-[#33a474] hover:bg-[#2a8a5f] border-[#33a474] hover:border-[#2a8a5f] transition-colors duration-300"
            /> -->
          </div>
        </template>
        <template v-else>
          <Button
            v-if="!userAnswerGroupId"
            label="开始测试"
            icon="pi pi-arrow-right"
            @click="handleStartTest"
            class="bg-[#33a474] hover:bg-[#2a8a5f] border-[#33a474] hover:border-[#2a8a5f] transition-colors duration-300"
          />
          <!-- 选项圆圈 -->
          <div v-if="initialQuestion && currentCategory" class="flex flex-col">
            <div class="flex items-center gap-20">
              <div class="text-[#88619a] text-2xl font-medium">不同意</div>
              <div class="flex flex-col items-center gap-2 justify-between h-[76px]"  v-for="(option, index) in currentCategory.options"   :key="option.id">
                <div
                  v-tooltip.top="option.label"
                  @click="nextQuestion(option.id)"
                  :class="[
                    'rounded-full cursor-pointer transition-all duration-300 ease-in-out transform hover:scale-110 hover:shadow-lg',
                    loading
                      ? 'opacity-50 cursor-not-allowed'
                      : 'hover:opacity-80',
                  ]"
                  :style="{
                    backgroundColor: getOptionColor(
                      initialQuestion.optionCategoryId,
                      index
                    ),
                    width: getOptionSize(initialQuestion.optionCategoryId, index),
                    height: getOptionSize(
                      initialQuestion.optionCategoryId,
                      index
                    ),
                    '--hover-color': getHoverColor(
                      getOptionColor(initialQuestion.optionCategoryId, index)
                    ),
                  }"
                ></div>
                <div class="text-sm text-gray-500">{{ option.label }}</div>
              </div>
              <div class="text-[#33a474] text-2xl font-medium">同意</div>
            </div>
            <!-- 加载状态 -->
            <div v-if="loading" class="mt-4 text-center">
              <div
                class="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-[#33a474]"
              ></div>
              <span class="ml-2 text-[#576071]">评估中...</span>
            </div>
          </div>
        </template>
      </div>
    </div>
    <div v-else class="text-2xl text-center mt-20">
      暂未登录，请您登录后进行测试
    </div>
  </div>
</template>

<style scoped>
/* 悬停效果 */
.rounded-full:hover {
  background-color: var(--hover-color) !important;
}

/* 点击效果 */
.rounded-full:active {
  transform: scale(0.95);
}

/* 禁用状态 */
.rounded-full.cursor-not-allowed:hover {
  transform: none;
  opacity: 0.5 !important;
}

/* 工具提示样式 */
:deep(.p-tooltip) {
  z-index: 1000;
}

:deep(.p-tooltip .p-tooltip-text) {
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 12px;
  border-radius: 6px;
  font-size: 14px;
  white-space: nowrap;
}

/* 加载动画 */
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
